package bank.local;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import bank.Account;
import bank.Bank;
import bank.InactiveException;
import bank.OverdrawException;

public class LocalBank implements Bank {

	//Map with all accounts
	private Map<String, LocalAccount> accounts = new HashMap<String, LocalAccount>();

	public String createAccount(String owner) throws IOException {
		String number = ""+accounts.size();
		LocalAccount account = new LocalAccount(owner, number);
		accounts.put(number, account);

		return number;
	}

	public boolean removeAccount(String number) throws IOException {
		LocalAccount account = accounts.get(number);
		if (account != null) {
			if (account.isActive()) {
				if (account.getBalance() == 0.0d) {
					account.remove();
					return true;
				}
			}
		}

		return false;
	}

	public Set<String> getAccountNumbers() {
		Set<String> numbers = new HashSet<String>();
		for (Account a : accounts.values()) {
			try {
				if (a.isActive()) {
					numbers.add(a.getNumber());
				}
			} catch (IOException e) {
			}
		}

		return numbers;
	}
	
	public Account getAccount(String number) {
		return accounts.get(number);
	}

	
	public void transfer(Account a, Account b, double amount) throws InactiveException, OverdrawException, IOException {
		synchronized (LocalBank.class) {
			a.withdraw(amount);
			b.deposit(amount);
		}
	}

}
